package com.unipay.order.api;

import com.unipay.common.result.Result;
import com.unipay.enums.PaymentTypeEnum;
import com.unipay.order.service.PaymentService;
import com.unipay.order.service.WeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @Author Chenmy
 * @Date 2023/7/18 21:51
 * @Desc TODO
 *    1、支付记录，添加
 *    2、更新，订单状态
 *    3、调用hosp接口，实现订单信息更新
 */
@Api(tags = "微信支付接口")
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;
    @Autowired
    private PaymentService paymentService;

    @ApiOperation(value = "下单，生成二维码")
    @GetMapping("/createNative/{orderId}")
    public Result createNative(
            @ApiParam(name = "orderId", value = "订单ID", required = true)
            @PathVariable("orderId") Long orderId
    ){
        Map map = weixinService.createNative(orderId);
        return Result.ok(map);
    }

    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(
            @ApiParam(name = "orderId", value = "订单ID", required = true)
            @PathVariable Long orderId
    ){
        Map<String, String> resultMap = weixinService.queryPayStatus(orderId);
        if (null == resultMap){
            return Result.fail().message("支付出错。。。");
        }
        // 支付成功
        if ("SUCCESS".equals(resultMap.get("trade_state"))){
            //（1）更新订单状态，处理支付结果
            String out_trade_no = resultMap.get("out_trade_no");
            paymentService.paySuccess(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            return Result.ok().message("支付成功！");
        }
        // 否则，支付中
        return Result.ok().message("支付中——");
    }

}
